package shoppingcart.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.xfengshopping.R;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import LOGIN.login;
import shoppingcart.fragment.adapter.OrderItemAdapter;
import shoppingcart.fragment.model.OrderDetail;
import shoppingcart.fragment.model.OrderDetailResponse;
import shoppingcart.fragment.model.OrderItem;
import shoppingcart.fragment.model.SaveOrderResponse;
import shoppingcart.fragment.model.SaveOrderParam;
import utils.TokenUtils;

public class CreateOrder extends AppCompatActivity {
    private static final String TAG = "CreateOrder";
    private static final int UNAUTHORIZED = 401;
    private final Handler handler = new Handler(Looper.getMainLooper());

    private TextView nameAddressText;
    private TextView phoneAddressText;
    private TextView addressText;
    private TextView priceText;
    private Button createOrderButton;
    private ImageView backCartButton;
    private RecyclerView orderItemsRecyclerView;

    private int addressId;
    private int[] cartItemIds;
    private String orderNo;
    private final List<OrderItem> orderItems = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_order);

        initViews();
        setupRecyclerView();

        Intent intent = getIntent();
        addressId = intent.getIntExtra("addressId", -1);
        cartItemIds = intent.getIntArrayExtra("cartItemIds");
        if (addressId == -1 || cartItemIds == null || cartItemIds.length == 0) {
            Log.e(TAG, "无效的参数");
            Toast.makeText(this, "订单信息不完整", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        String addressName = intent.getStringExtra("addressName");
        String addressPhone = intent.getStringExtra("addressPhone");
        String addressDetail = intent.getStringExtra("addressDetail");

        nameAddressText.setText(addressName);
        phoneAddressText.setText(addressPhone);
        addressText.setText(addressDetail);

        setupButtonListener();
        submitOrder();
    }

    private void initViews() {
        nameAddressText = findViewById(R.id.name_address);
        phoneAddressText = findViewById(R.id.phone_address);
        addressText = findViewById(R.id.address);
        priceText = findViewById(R.id.priceText);
        createOrderButton = findViewById(R.id.create);
        backCartButton=findViewById(R.id.back_to_cart);
        orderItemsRecyclerView = findViewById(R.id.recyclerView);
    }

    private void setupRecyclerView() {
        orderItemsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        OrderItemAdapter adapter = new OrderItemAdapter(orderItems);
        orderItemsRecyclerView.setAdapter(adapter);
    }

    private void setupButtonListener() {
        createOrderButton.setOnClickListener(v -> {
            createOrderButton.setEnabled(false);
        });
        backCartButton.setOnClickListener(v -> {
            finish();
        });
    }

    private void submitOrder() {
        new Thread(() -> {
            try {
                String token = TokenUtils.getToken(this);
                String response = createOrderRequest(token, addressId, cartItemIds);
                SaveOrderResponse saveOrderResponse = new Gson().fromJson(response, SaveOrderResponse.class);

                if (saveOrderResponse != null && saveOrderResponse.getResultCode() == 200) {
                    orderNo = saveOrderResponse.getData();
                    fetchOrderDetails(orderNo, token);
                } else {
                    String message = saveOrderResponse != null ? saveOrderResponse.getMessage() : "未知错误";
                    showError("创建订单失败：" + message);
                }
            } catch (Exception e) {
                showError("创建订单失败：" + e.getMessage());
            }
        }).start();
    }

    private String createOrderRequest(String token, int addressId, int[] cartItemIds) throws Exception {
        String url = "http://47.99.134.126:28019/api/v1/saveOrder";
        SaveOrderParam saveOrderParam = new SaveOrderParam(addressId, cartItemIds);

        HttpURLConnection connection = null;
        try {
            URL urlObj = new URL(url);
            connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("token", token);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);

            try (OutputStream os = connection.getOutputStream()) {
                os.write(new Gson().toJson(saveOrderParam).getBytes(java.nio.charset.StandardCharsets.UTF_8));
            }

            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                return readInputStream(connection.getInputStream());
            } else {
                String errorResponse = readInputStream(connection.getErrorStream());
                throw new IOException("HTTP Error: " + responseCode + " " + errorResponse);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private void fetchOrderDetails(String orderNo, String token) throws Exception {
        String url = "http://47.99.134.126:28019/api/v1/order/" + orderNo;

        HttpURLConnection connection = null;
        try {
            URL urlObj = new URL(url);
            connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("token", token);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);

            int responseCode = connection.getResponseCode();
            String response = readInputStream(connection.getInputStream());
            OrderDetailResponse orderDetailResponse = new Gson().fromJson(response, OrderDetailResponse.class);

            if (orderDetailResponse != null && orderDetailResponse.getResultCode() == 200) {
                updateOrderUI(orderDetailResponse);
            } else {
                showError("获取订单详情失败");
            }
        } catch (IOException e) {
            showError("网络错误：" + e.getMessage());
        }
    }

    private void updateOrderUI(final OrderDetailResponse orderDetailResponse) {
        handler.post(() -> {
            if (orderDetailResponse != null && orderDetailResponse.getData() != null) {
                OrderDetail orderDetail = orderDetailResponse.getData();
                orderItems.clear();
                if (orderDetail.getNewBeeMallOrderItemVOS() != null) {
                    orderItems.addAll(orderDetail.getNewBeeMallOrderItemVOS());
                }

                // 获取适配器并通知数据变化
                OrderItemAdapter adapter = (OrderItemAdapter) orderItemsRecyclerView.getAdapter();
                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }

                if (priceText != null && orderDetail.getTotalPrice() > 0) {
                    priceText.setText(String.format("¥%d", orderDetail.getTotalPrice()));
                }

                createOrderButton.setText("订单已创建");
                createOrderButton.setEnabled(false);
            } else {
                showError("订单数据为空");
            }
        });
    }

    private void showError(final String message) {
        handler.post(() -> {
            Toast.makeText(this, message, Toast.LENGTH_LONG).show();
            createOrderButton.setEnabled(true);
        });
    }

    private String readInputStream(InputStream inputStream) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        }
    }
}